package myJs.cps

import japgolly.scalajs.react.ScalaFnComponent
import myJs.myPkg.Hooks._
import myJs.myPkg.rSelect._
import myJs.myPkg.jquery.{$, JQuery}
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.html

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSON
import japgolly.scalajs.react.vdom.all._
import cats.effect._
import japgolly.scalajs.react.util.EffectCatsEffect._

object PureRSelectCp {

  case class Props(
      optionMap: SeqMap[String, String],
      onChange: String => SyncIO[Unit],
      name: String = "",
      value: String = "",
      registerOptions: RegisterOptions = RegisterOptions()
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val (beforeOptionMap, setBeforeOptionMap) = useState(SeqMap[String, String]())
    val firstUpdate = useRef(true)
    val useController = ReactHookForm.useController(options =
      UseControllerOptions(
        name = props.name,
        defaultValue = s"${props.value}"
      )
    )
    val field = useController.field
    val fieldState = useController.fieldState

    object FTool {

      def onChange = (so: SelectOption) => {
        val v = so.value
        field.onChange(v)
        props.onChange(v)
      }

    }

    useEffect(
      {
        if (props.value != field.value.asInstanceOf[String]) {
          IO {
            field.onChange(props.value)
          }
        } else IO {}
      },
      List(props.value)
    )

    val options = props.optionMap.map { case (k, v) =>
      SelectOption(value = k, label = v)
    }.toList
    val selectOption = if (props.optionMap.isDefinedAt(props.value)) {
      js.defined(SelectOption(value = props.value, label = props.optionMap(props.value)))
    } else js.undefined

    div(
      SelectSingle(
        onChange = FTool.onChange,
        options = options,
        placeholder = "click to choose",
        name = field.name,
        value = selectOption,
        ref = field.ref
      ),
      fieldState.error.map { error =>
        small(className := "help-block", error.message)
      }
    )

  }

}
